package com.example.echoewish.ui.my_activity.my_publish_activity;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.echoewish.econstant.Constant;
import com.example.echoewish.econstant.UserInfo;
import com.example.echoewish.pojo.MyPublishPost;
import com.example.echoewish.repository.PostMessageRepository;
import com.example.echoewish.util.LogUtil;

import java.io.IOException;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyPublishViewModel extends ViewModel {
    public final  static  int CHANGE_LIST_VIEW=3;
    public final  static  int DELETE_POST_SUCCESS=4;
    public final  static  int DELETE_POST_FAIL=5;


    MutableLiveData<List<MyPublishPost>> myPublishPostMutableLiveData;
    MutableLiveData<Integer> deletePostIdMutableLiveData;
    MutableLiveData<String> responseMutableLiveData;

    public MyPublishViewModel()
    {
        myPublishPostMutableLiveData=new MutableLiveData<>();
        deletePostIdMutableLiveData=new MutableLiveData<>();
        responseMutableLiveData=new MutableLiveData<>();
    }

    public void getMyPublishByUserId()
    {
        PostMessageRepository.getInstance().queryMyPublishPostByUserId(UserInfo.getInstance().UserId,new GetMyPublishCallBack());
    }

    public void deletePostByPostId()
    {
        PostMessageRepository.getInstance().deletePost(deletePostIdMutableLiveData.getValue(),new DeletePostCallBack());
    }

    private class GetMyPublishCallBack implements Callback<List<MyPublishPost>>
    {
        @Override
        public void onResponse(Call<List<MyPublishPost>> call, Response<List<MyPublishPost>> response) {
            myPublishPostMutableLiveData.postValue(response.body());
        }

        @Override
        public void onFailure(Call<List<MyPublishPost>> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"获取我的帖子信息 回调失败"+t);
            myPublishPostMutableLiveData.postValue(null);
        }
    }

    private class DeletePostCallBack implements Callback<ResponseBody>
    {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                responseMutableLiveData.postValue(response.body().string());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"删除我的帖子信息 回调失败"+t);
            responseMutableLiveData.postValue(Constant.HTTPS_GET_CALLBACK_FAIL);
        }
    }
}
